// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package server

import (
	"apiote.xyz/p/szczanieckiej/traffic"
	traffic_errors "apiote.xyz/p/szczanieckiej/traffic/errors"

	"net/http"
	"strconv"
	"strings"
	"time"
)

func parseAccept(headers []string) (map[uint]struct{}, error) {
	result := map[uint]struct{}{}
	for _, header := range headers {
		if header == "" {
			header = "EMPTY"
		}
		header, _ := strings.CutPrefix(header, "application/")
		header, _ = strings.CutSuffix(header, "+bare")
		a, err := strconv.ParseUint(header, 10, 0)
		if err != nil {
			continue
		}
		result[uint(a)] = struct{}{}
	}
	if len(result) == 0 {
		return result, ServerError{
			code:  http.StatusBadRequest,
			field: "Accept",
			value: "",
		}
	}
	return result, nil
}

func parseDate(dateString string, feedID string, t *traffic.Traffic) (traffic.Validity, time.Time, error) {
	versionCode, date, err := traffic.ParseDate(dateString, feedID, t)
	if err != nil {
		if _, ok := err.(traffic_errors.NoVersionError); ok {
			return versionCode, date, ServerError{
				code:  http.StatusNotFound,
				field: "date",
				value: dateString,
				err:   err,
			}
		} else {
			return versionCode, date, ServerError{
				code:  http.StatusBadRequest,
				field: "date",
				value: dateString,
				err:   err,
			}
		}
	}
	return versionCode, date, nil
}
